import {deepCopy} from './copy';

/**
 * some test code
 * const a = {
    'user': {
      'api': {
        'name': 'test'
      }
    }
  };
 console.log(getProperty(a, 'user.api.name'));
 console.log(getProperty(a, 'user.name'));
 setProperty(a, 'user.api.name', 123);
 setProperty(a, 'user.test', 222);
 console.log(a);
 * */

export function getProperty(object: any, name: string) {
  let value = object;
  const propNames = name.split('.');
  for (const propName of propNames) {
    try {
      value = value[propName];
    } catch (e) {
      value = '';
    }
  }
  return value;
}

export function setProperty(object: any, name: string, value: any) {
  if (object) {
    let _object = object;
    const propNames = name.split('.');
    for (let i = 0; i < propNames.length; i++) {
      if (i !== propNames.length - 1) {
        _object = _object[propNames[i]] || null;
      } else {
        if (_object) {
          _object[propNames[i]] = value;
        } else {
          break;
        }
      }
    }
  }
}

